package xuan.mall.system.infrastructure.security.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.io.IOException;

/**
 * @author: rongxuanzhou
 * @create: 2025/5/31
 * @Description:
 */
public class MallLoginFilter extends UsernamePasswordAuthenticationFilter {

    public MallLoginFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain
    ) throws IOException, ServletException {
        int contentLength = request.getContentLength();
        if (contentLength == 0) {
            sendError(response, "请求体为空");
            return;
        }

        if (contentLength > 4096) { // 合理限制大小
            sendError(response, "请求体过大");
            return;
        }

        chain.doFilter(request, response);
    }

    private void sendError(ServletResponse response, String msg) throws IOException {
        ((HttpServletResponse) response).sendError(HttpStatus.BAD_REQUEST.value(), msg);
    }
}
